<?php

namespace app\api\controller;

use support\Request;
use app\ai\model\Banner;
use app\ai\model\IndexTemplate;
use app\ai\model\TemplateType;
use app\ai\model\Template;
use app\ai\model\TemplatePrice;
use app\ai\model\SignLog;
use app\ai\model\BalanceLog;
use app\ai\model\User;
use app\ai\model\Level;
use app\ai\model\AddTask;
use app\ai\model\Task;
use app\ai\model\ChargeSetting;
use think\facade\Db;
use plugin\saiadmin\app\logic\system\SystemConfigLogic;
use plugin\saiadmin\exception\ApiException;
use plugin\saiadmin\utils\Arr;

//系统常用的接口管理
class SystemController
{
    /**
     * 轮播图和广告管理
     */
    public function banner(Request $request)
    {
        $list = Banner::select();
        return json(['code'=>200,'msg'=>'success','data'=>$list]);
    }

    /**
     * 首页模板展示设置
     */
    public function indexTemplate(Request $request)
    {
        $list = IndexTemplate::with('template')->select();
        return json(['code'=>200,'msg'=>'success','data'=>$list]);
    }

    /**
     * 所有模板分类
     */
    public function templateType(Request $request)
    {
        $list = TemplateType::select();
        return json(['code'=>200,'msg'=>'success','data'=>$list]);
    }

    /**
     * 获取指定模板分类下的所有模板
     */
    public function template(Request $request ,$id)  {
        if(!$id) {
            $id = 1; //默认分类1的模板
        }
        $list = Template::where('type_id',$id)->where('status',1)->select();
        return json(['code'=>200,'msg'=>'success','data'=>$list]);
    }

    /**
     * 获取指定模板的价格列表
     */
    public function templatePrice(Request $request,$id){
        $list = TemplatePrice::where('template_id',$id)->select();
        return json(['code'=>200,'msg'=>'success','data'=>$list]);
    }

    /**
     * 用户签到
     */
    public function sign(Request $request){
        $uid = $request->userData['user_id'];

        // 先检查用户是否存在
        $userInfo = User::find($uid);
        if (!$userInfo) {
            return json(['code'=>400,'msg'=>'用户不存在','data'=>['uid'=>$uid]]);
        }

        //获取签到配置相关
        $logic = new SystemConfigLogic();
        $config = $logic->getGroup('task_config');
        if (!$config) {
            throw new ApiException('未设置任务配置');
        }
        $sign_coin = Arr::getConfigValue($config, 'sign_coin');

        //检查是否已经签到
        $check = SignLog::where('uid', $uid)->whereTime('create_time', 'today')->find();
        if ($check) {
            return json(['code'=>400,'msg'=>'今日已经签到了！','data'=>['uid'=>$uid]]);
        }

        // 开启事务
        Db::startTrans();
        try {
            // 添加签到记录
            SignLog::create(['uid' => $uid]);
            
            // 添加金币变动记录
            BalanceLog::create([
                'user_id' => $uid,
                'type' => 1,
                'price' => $sign_coin,
                'before'=> $userInfo->coin_balance,
                'after'=> $userInfo->coin_balance + $sign_coin,
                'balance' => $sign_coin,
                'remarks' => '签到奖励'
            ]);
            
            // 更新用户金币余额
            $userInfo->coin_balance = $userInfo->coin_balance + $sign_coin;
            $userInfo->save();
            
            // 提交事务
            Db::commit();
            
            return json(['code'=>200,'msg'=>'签到成功','data'=>[
                'uid'=>$uid,
                'coin_balance'=>$userInfo->coin_balance,
                'diamond_balance'=>$userInfo->diamond_balance
            ]]);
        } catch(\Exception $e) {
            // 回滚事务
            Db::rollback();
            return json(['code'=>400,'msg'=>$e->getMessage(),'data'=>['uid'=>$uid]]);
        }
    }


    /**
     * 获取VIP价格列表
     */
    public function vipPrice(Request $request){
        $list = Level::select();
        return json(['code'=>200,'msg'=>'success','data'=>$list]);
    }

    /**
     * 获取每日任务
     */
    public function task(Request $request){
        $list = AddTask::where('status',1)->select();
        return json(['code'=>200,'msg'=>'success','data'=>$list]);
    }


    /***
     * 获取充值档位
     */
    public function recharge(Request $request){
        $list = ChargeSetting::select();
        return json(['code'=>200,'msg'=>'success','data'=>$list]);
    }

    /**
     * 首页查看用户分享信息
     */
    public function share(Request $request){
        $page = (int)$request->input('page', 1);
        $limit = (int)$request->input('limit', 10);
        
        $list = Task::alias('t')
            ->join('ai_user u', 'u.id = t.uid')
            ->join('ai_template tp', 'tp.id = t.template_id')
            ->join('ai_template_price p', 'p.template_id = t.template_id AND p.sort = t.articulation')
            ->where('t.is_share', 1)
            ->field([
                't.id',
                't.original_img_url',
                't.result_img_url',
                't.template_id',
                't.view',
                // 't.articulation',
                'u.nickname',
                'u.avatar',
                'u.level',
                'tp.name as template_name',
                'p.name as price_name'
            ])
            ->order('t.create_time', 'desc')
            ->paginate([
                'list_rows' => $limit,
                'page' => $page,
            ]);
            
        return json([
            'code' => 200,
            'msg' => 'success',
            'data' => [
                'list' => $list->items(),
                'total' => $list->total(),
                'last_page' => $list->lastPage(),
                'current_page' => $list->currentPage(),
            ]
        ]);
    }

    /**
     * 获取首页热门的模板
     */
    public function recommend(Request $request){
        $list = Template::where('is_hot', 1)->select();
        return json(['code'=>200,'msg'=>'success','data'=>$list]);
    }
}
